<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>User 1 Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }

        #messages {
            list-style: none;
            padding: 0;
        }

        #messages li {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
            max-width: 80%;
        }

        .user1-msg {
            background-color: #e3f2fd;
            margin-left: auto;
        }

        .user2-msg {
            background-color: #f5f5f5;
        }

        .input-container {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }

        input[type="text"] {
            flex-grow: 1;
            padding: 8px;
        }

        button {
            padding: 8px 20px;
            cursor: pointer;
        }

        .system-msg {
            color: #666;
            font-size: 0.9em;
        }

        #user-status {
            margin-top: 10px;
        }

        .online {
            color: green;
        }

        .offline {
            color: red;
        }
    </style>
</head>

<body>
<h1>User 1 (ID: 1)</h1>
<ul id="messages"></ul>
<div class="input-container">
    <input type="text" id="messageInput" placeholder="输入消息...">
    <button onclick="sendMessage()">发送</button>
</div>
<div id="user-status">对方状态: <span id="status-text">未知</span></div>

<script>
    const userId = 1;
    const receiverId = 2;
    let socket;
    let reconnectAttempts = 0;
    let reconnectInterval;

    function connect() {
        socket = new WebSocket(`ws://118.178.134.24:8060/ws?userId=${userId}`);

        socket.onopen = function () {
            appendMessage("连接已建立（用户1）", "system");
            alert("连接成功！");
            reconnectAttempts = 0;
            clearInterval(reconnectInterval);
            reconnectInterval = null;
            // 获取最近两天的聊天记录
            getRecentMessages();
        };

        socket.onmessage = function (event) {
            try {
                const msg = JSON.parse(event.data);
                const isUser2 = msg.senderId === 2;
                appendMessage(msg.content, isUser2 ? "user2-msg" : "user1-msg");
            } catch (error) {
                console.error("消息解析失败:", error);
            }
        };

        socket.onclose = function () {
            appendMessage("连接已关闭（用户1）", "system");
            alert("连接已关闭！");
            if (!reconnectInterval) {
                reconnectInterval = setInterval(attemptReconnect, 60000);
            }
        };

        socket.onerror = function (error) {
            console.error("WebSocket 发生错误:", error);
        };
    }

    function sendMessage() {
        const input = document.getElementById("messageInput");
        const content = input.value.trim();
        if (!content) return;

        const message = {
            senderId: userId,
            receiverId: receiverId,
            content: content,
            type: 1,
            status: 1,
            isCompressed: false,
            sequenceNumber: Date.now(),
            sendTime: Date.now() // 使用时间戳
        };

        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify(message));
            appendMessage(content, "user1-msg");
            input.value = "";
        } else {
            alert("连接已断开，无法发送消息");
        }
    }

    function appendMessage(content, className) {
        const messages = document.getElementById("messages");
        const li = document.createElement("li");
        li.className = className;
        li.innerHTML = content;
        messages.appendChild(li);
        messages.scrollTop = messages.scrollHeight;
    }

    function attemptReconnect() {
        if (reconnectAttempts >= 5) {
            clearInterval(reconnectInterval);
            reconnectInterval = null;
            appendMessage("连续五分钟尝试重新连接失败，停止尝试", "system");
            return;
        }
        reconnectAttempts++;
        appendMessage(`尝试重新连接（第 ${reconnectAttempts} 次）`, "system");
        connect();
    }

    function checkUserStatus() {
        // 修正 URL，添加协议头
        fetch(`http://127.0.0.1:8060/user-status/${receiverId}/isOnline`)
            .then(response => response.json())
            .then(data => {
                const statusText = document.getElementById("status-text");
                if (data) {
                    statusText.textContent = "在线";
                    statusText.className = "online";
                } else {
                    statusText.textContent = "离线";
                    statusText.className = "offline";
                }
            })
            .catch(error => {
                console.error("检查用户状态失败:", error);
                const statusText = document.getElementById("status-text");
                statusText.textContent = "未知";
                statusText.className = "";
            });
    }

    function getRecentMessages() {
        const endTime = new Date();
        const startTime = new Date(endTime.getTime() - 2 * 24 * 60 * 60 * 1000);

        // 修正 URL，添加协议头
        fetch(`http://127.0.0.1:8060/messages/history?senderId=${userId}&receiverId=${receiverId}&startTime=${startTime}&endTime=${endTime}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    data.data.forEach(message => {
                        const isUser2 = message.senderId === 2;
                        appendMessage(message.content, isUser2 ? "user2-msg" : "user1-msg");
                    });
                } else {
                    console.error("获取最近聊天记录失败:", data.message);
                }
            })
            .catch(error => {
                console.error("获取最近聊天记录失败:", error);
            });
    }

    // 初始检查用户状态
    checkUserStatus();
    // 每 10 秒轮询一次用户状态
    setInterval(checkUserStatus, 10000);

    connect();
</script>
</body>

</html>